package cn.com.code.generator.service.impl;

import cn.com.code.generator.annotation.MethodAnnotation;
import cn.com.code.generator.dao.UserDao;
import cn.com.code.generator.entity.User;
import cn.com.code.generator.service.UserService;
import cn.com.code.generator.thread.MultiExecutor;
import cn.com.code.generator.thread.ThreadExecution;
import cn.com.code.generator.utils.BaseUtil;
import cn.com.code.generator.vo.SaveUserReqVO;
import cn.com.code.generator.vo.UserReqPageVO;
import cn.com.code.generator.vo.UserRespPageVO;
import cn.com.do1.dsf.compont.mysql.annotation.DataSource;
import cn.com.do1.dsf.compont.mysql.utils.PageUtils;
import cn.com.do1.dsf.compont.mysql.utils.Query;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private UserDao userDao;
    @Override
    @MethodAnnotation
    public PageUtils<UserRespPageVO> searchUserPage(UserReqPageVO params) {
        if(BaseUtil.isNotEmpty(params.getName())){
            params.setName("%"+params.getName()+"%");
        }
        Page page = params.getPager();
        List<UserRespPageVO> list=userDao.searchUserPage(page,params);
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    @DataSource(name = "second")
    public PageUtils<UserRespPageVO> searchUserPageParam(Map<String, Object> params) {
        BaseUtil.putMapLike(params, "nameUser",params.get("nameUser"));
        Query query = new Query(params);
        Page page = query.getPage();
        List<UserRespPageVO> list = userDao.searchUserPageParam(page,query);
        page.setRecords(list);
        return new PageUtils<>(page);
    }

    @Override
    public List<String> saveUser(SaveUserReqVO users) {
        Map<String, Object> variables = new ConcurrentHashMap<>();
        variables.put("1",1);
        variables.put("2",2);
        Map<String, List<String>> returnResp = new ConcurrentHashMap<>(users.getAge().size());
        ThreadExecution threadExecution = new BatchSaveUserThreadExecutionImpl(users.getName(),variables,returnResp);
        //分3批，如果300个，每批100
        MultiExecutor.exec(threadExecution,3, users.getAge());
        List<String> ids = new ArrayList<>();
        returnResp.forEach((k,v) ->{
            logger.info("key={},value={}", k,JSONObject.toJSONString(v));
            ids.addAll(v);
        });
        return ids;
    }
}
